package com.sanq.product.books.controller;

import com.sanq.product.books.config.Redis;
import com.sanq.product.books.entity.vo.DiscussVo;
import com.sanq.product.books.entity.vo.UsersVo;
import com.sanq.product.books.service.DiscussService;
import com.sanq.product.config.utils.annotation.LogAnnotation;
import com.sanq.product.config.utils.entity.Pager;
import com.sanq.product.config.utils.entity.Pagination;
import com.sanq.product.config.utils.entity.Response;
import com.sanq.product.config.utils.web.JsonUtil;
import com.sanq.product.redis.service.JedisPoolService;
import com.sanq.product.security.annotation.IgnoreSecurity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@RestController
@RequestMapping("/app/discuss")
public class DiscussController {

	@Resource
	private DiscussService discussService;
	@Resource
	private JedisPoolService jedisPoolService;

	@LogAnnotation(description = "通过ID得到详情")
	@GetMapping(value="/get/{id}")
	public Response getById(HttpServletRequest request, @PathVariable("id") Integer id) {
		DiscussVo discussVo = discussService.findById(id);

		return discussVo != null ? new Response().success(discussVo) : new Response().failure();
	}

	@LogAnnotation(description = "删除数据")
	@DeleteMapping(value="/delete")
	public Response deleteById(HttpServletRequest request, @RequestBody DiscussVo discussVo) {

		int result = discussService.delete(discussVo);
		return result == 1 ? new Response().success() : new Response().failure();
	}

	@IgnoreSecurity
	@LogAnnotation(description = "分页查询数据")
	@GetMapping(value="/list")
	public Response findListByPager(HttpServletRequest request, DiscussVo discussVo, Pagination pagination) {
		UsersVo usersVo = JsonUtil.json2Obj(jedisPoolService.get(Redis.ReplaceKey.getTokenUser(discussVo.getToken())), UsersVo.class);

		if (null !=usersVo)
			discussVo.setUserId(usersVo.getId());

		Pager<DiscussVo> pager = discussService.findListByPage(discussVo, pagination);

		return pager != null ? new Response().success(pager) : new Response().failure();
	}

	@LogAnnotation(description = "添加数据")
	@PostMapping(value="/save")
	public Response add(HttpServletRequest request, @RequestBody DiscussVo discussVo) {

		UsersVo usersVo = JsonUtil.json2Obj(jedisPoolService.get(Redis.ReplaceKey.getTokenUser(discussVo.getToken())), UsersVo.class);

		discussVo.setUserId(usersVo.getId());
		int result = discussService.save(discussVo);

		return result == 1 ? new Response().success() : new Response().failure();
	}

	@IgnoreSecurity
	@LogAnnotation(description = "根据小说ID获取书籍评分， 评论数， 人气值")
	@GetMapping(value="/findTotalsByBookId")
	public Response findTotalsByBookId(HttpServletRequest request, Integer bookId) {

		Map<String, Object> map =  discussService.findTotalsByBookId(bookId);

		return map != null && !map.isEmpty() ? new Response().success(map) : new Response().failure();
	}
}